package com.aliyun.heiyu.powermaster.server.strategy;

import com.aliyun.heiyu.common.util.HttpUtil;
import com.aliyun.heiyu.common.util.PropertiesUtil;
import com.aliyun.heiyu.common.util.StringUtil;
import com.aliyun.heiyu.powermaster.server.dao.entity.DeviceCommonEntity;
import com.aliyun.heiyu.powermaster.server.manager.*;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

public class StrategyMonitor {
    private static Logger logger = LoggerFactory.getLogger(StrategyMonitor.class);

    private ThunderManager thunderDataProvider;
    private DeviceManager deviceManager;

    public StrategyMonitor() {
        this.thunderDataProvider = new ThunderManagerImpl();
        this.deviceManager = DeviceManagerImpl.getInstance();
    }

    /**
     * 获取某个point的cpu使用率，point：0表示当前点、-1表示前一个点、1表示下一个点
     */
    public String getCPUUsage(String sn, Integer point) {
        if (point > 0) {
            return getAICondition(sn, point, "cpu_usage");
        }
        Map<String, String> map = thunderDataProvider.getServerPowerInfoBefore(sn, point * (-1));
        if (map == null) {
            return null;
        }
        String cpu_usage = map.get("cpu_usage");
        logger.debug("server: " + sn + ", cpu usage in checkPoint " + point + ": " + cpu_usage);
        return cpu_usage;
    }

    /**
     * 获取某个point的cpu频率，point：0表示当前点、-1表示前一个点、1表示下一个点
     */
    public String getCPUFreqUsage(String sn, Integer point) {
        String cpuFreq;
        if (point > 0) {
            cpuFreq = getAICondition(sn, point, "cpu_freq");
        }
        Map<String, String> map = thunderDataProvider.getServerPowerInfoBefore(sn, point * (-1));
        if (map == null) {
            return null;
        }
        cpuFreq = map.get("cpu_freq");
        if (cpuFreq == null) {
            return null;
        }
        try{

            double cpuFreqUsage = Double.parseDouble(cpuFreq) / 2500;
            return String.valueOf(cpuFreqUsage);
        } catch (Exception e){
            logger.error("static data error,cpu_freq = 0 or null",e);
        }
        logger.debug("server: " + sn + ", cpu freq in checkPoint " + point + ": " + cpuFreq);
        return null;
    }

    /**
     * 获取某个point的机房温度，point：0表示当前点、-1表示前一个点、1表示下一个点
     */
    public String getTemp(String sn, Integer point) {
        Map<String, String> map = thunderDataProvider.getServerPowerInfoBefore(sn, point * (-1));
        if (map == null) {
            return null;
        }
        String temp = map.get("inlet_temp");
        logger.debug("server: " + sn + ", inlet_temp in checkPoint " + point + ": " + temp);
        return temp;
    }

    /**
     * 获取某个point的功耗值，point：0表示当前点、-1表示前一个点、1表示下一个点
     */
    public String getPower(String sn, Integer point) {
        if (point > 0) {
            return getAICondition(sn, point, "server_power");
        }
        Map<String, String> map = thunderDataProvider.getServerPowerInfoBefore(sn, point * (-1));
        if (map == null) {
            return null;
        }
        String power = map.get("server_power");
        logger.debug("server: " + sn + ", power in checkPoint " + point + ": " + power);
        return power;
    }

    /**
     * 获取某个point的功耗值占最大功耗值的比例，point：0表示当前点、-1表示前一个点、1表示下一个点
     */
    public String getPowerUsage(String sn, Integer point) {
        String power;
        if (point > 0) {
            power = getAICondition(sn, point, "server_power");
            logger.debug("ai 1 === power ===   "+power);
        }
        Map<String, String> map = thunderDataProvider.getServerPowerInfoBefore(sn, point * (-1));
        if (map == null) {
            return null;
        }
        power = map.get("server_power");
        if (power == null) {
            return null;
        }
        DeviceCommonEntity deviceCommon = deviceManager.findOneDeviceCommon(sn);
        if(deviceCommon == null || StringUtil.convertDouble(deviceCommon.getRated_power()) == 0){
            return null;
        }
        try{
            double powerUsage = Double.parseDouble(power) / StringUtil.convertDouble(deviceCommon.getRated_power());
            logger.debug("server: " + sn + ", powerUsage in checkPoint " + point + ": " + powerUsage);
            return String.valueOf(powerUsage);
        } catch (Exception e){
            logger.error("static data error,cpu_freq = 0 or null",e);
        }

        return null;
    }

    /**
     * 检测qos是否受损
     */
    public boolean isQOSDamaged(String sn) {
        return false;
    }

    //todo 直接读库
    private String getAICondition(String sn, Integer point, String key) {
        AIConditionRequest request = new AIConditionRequest();
        request.setSn(sn);
        request.setPoint(String.valueOf(point));
        String json = new JSONObject(request).toString();
        String url = PropertiesUtil.getValue("serverIp.properties", "aiStategyConditionUrl");
        JSONObject jsonObject = HttpUtil.postRequest(json, url);
        if (jsonObject == null || !"0".equals(jsonObject.get("err_code"))) {
            logger.error("http error: with url: " + url + ", with json:" + json + ", with response: " + jsonObject);//请求失败
            return null;
        } else if (jsonObject.getJSONObject("data") == null) {
            logger.error("http error: with url: " + url + ", with json: " + json + ", with data: " + jsonObject);//请求失败
            return null;
        } else {
            JSONObject data = jsonObject.getJSONObject("data");
            logger.info("http ai success url"+url);
            return data.getString(key);
        }
    }

    public class AIConditionRequest {
        private String sn;
        private String point;

        public String getSn() {
            return sn;
        }

        public void setSn(String sn) {
            this.sn = sn;
        }

        public String getPoint() {
            return point;
        }

        public void setPoint(String point) {
            this.point = point;
        }

        @Override
        public String toString() {
            return "AIConditionRequest{" +
                "sn='" + sn + '\'' +
                ", point='" + point + '\'' +
                '}';
        }
    }

    private class AIConditionResponse {
        private String err_code;
        private String err_msg;
        private Data data;

        private class Data {
            private String power;
            private String cpuFreq;
            private String cpuUsage;

            public String getPower() {
                return power;
            }

            public void setPower(String power) {
                this.power = power;
            }

            public String getCpuFreq() {
                return cpuFreq;
            }

            public void setCpuFreq(String cpuFreq) {
                this.cpuFreq = cpuFreq;
            }

            public String getCpuUsage() {
                return cpuUsage;
            }

            public void setCpuUsage(String cpuUsage) {
                this.cpuUsage = cpuUsage;
            }

            @Override
            public String toString() {
                return "AIConditionResponse{" +
                    "power='" + power + '\'' +
                    ", cpuFreq='" + cpuFreq + '\'' +
                    ", cpuUsage='" + cpuUsage + '\'' +
                    '}';
            }
        }

        public String getErr_code() {
            return err_code;
        }

        public void setErr_code(String err_code) {
            this.err_code = err_code;
        }

        public String getErr_msg() {
            return err_msg;
        }

        public void setErr_msg(String err_msg) {
            this.err_msg = err_msg;
        }

        public Data getData() {
            return data;
        }

        public void setData(Data data) {
            this.data = data;
        }

        @Override
        public String toString() {
            return "AIConditionResponse{" +
                "err_code='" + err_code + '\'' +
                ", err_msg='" + err_msg + '\'' +
                ", data=" + data +
                '}';
        }
    }

}
